package com.xiaozhen.device.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.domain.R;
import com.xiaozhen.common.core.domain.device.Device;
import com.xiaozhen.common.core.domain.device.queryParams.DeviceQueryParam;
import com.xiaozhen.common.core.domain.driver.param.ModbusParam;
import com.xiaozhen.common.core.domain.driver.vo.ModbusDriverVo;
import com.xiaozhen.device.service.DeviceService;
import com.xiaozhen.security.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/11/1 11:28
 * @description:
 */
@Api(tags = "设备接口")
@RestController
@RequestMapping("device")
public class DeviceController extends BaseController {

    @Autowired
    private DeviceService deviceService;

    @ApiOperation("获取设备列表")
    @GetMapping("/list")
    public AjaxResult list(DeviceQueryParam queryParam) {
        Page<Device> page = startPage();
        Page<Device> deviceList = deviceService.selectDeviceList(page, queryParam);
        return getDataTable(deviceList);
    }

    @ApiOperation("新增设备")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody Device device) {
        if (!deviceService.checkDeviceNameUnique(device)) {
            return AjaxResult.error("新增设备'" + device.getDeviceName() + "'失败，设备名称已存在");
        }
        device.setCreateBy(getCurrentUserId());
        device.setCreateTime(LocalDateTime.now());
        return toAjax(deviceService.insertDevice(device));
    }

    @ApiOperation("修改设备")
    @PutMapping("/update")
    public AjaxResult edit(@Validated @RequestBody Device device) {
        if (!deviceService.checkDeviceNameUnique(device)) {
            return AjaxResult.error("修改设备'" + device.getDeviceName() + "'失败，设备名称已存在");
        }
        device.setUpdateBy(getCurrentUserId());
        device.setUpdateTime(LocalDateTime.now());
        return toAjax(deviceService.updateDevice(device));
    }

    @ApiOperation("删除设备")
    @DeleteMapping("/{deviceId}")
    public AjaxResult remove(@PathVariable Long deviceId) {
        return toAjax(deviceService.deleteDeviceById(deviceId));
    }

    /**
     * 根据设备ID查询出所在驱动和属性信息
     */
    @ApiOperation("获取MODBUS的设备详细信息")
    @GetMapping("/getModbusDeviceInfo")
    public R<ModbusDriverVo> getModbusDeviceInfo(@RequestParam("deviceId") Long deviceId) {
        ModbusDriverVo modbusDriverVo = deviceService.getModbusDeviceInfo(deviceId);
        return R.ok(modbusDriverVo);
    }
}
